/* eslint-disable react/sort-comp */
/* eslint-disable array-callback-return */
/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { debounce } from 'lodash';
import {
  Card,
  Form,
  Row,
  Col,
  DatePicker,
  Input,
  InputNumber,
  Button,
  Modal,
  Radio,
  Spin,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import DownloadBar from '@/components/DownloadBar';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import styles from './style.less';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const RadioGroup = Radio.Group;
const dataFormat = 'YYYY-MM-DD';

@connect(({ cost, loading }) => ({
  cost,
  submitLoading: loading.effects['cost/getCostList'],
  outLoading: loading.effects['cost/giveCostOut'],
}))
@Form.create()
export default class Cost extends PureComponent {
  state = {
    visible: false,
    detailId: '',
  };

  componentDidMount() {
    this.getCostList();
  }

  handleStandardTableChange = e => {
    this.getCostList(e.current, '', '', '', e.pageSize);
  };

  getCostList = (page = 1, id, time, close, size = 10) => {
    const {
      dispatch,
      form: { validateFields },
    } = this.props;
    const { detailId, s_time } = this.state;
    if ((!detailId && !id) || close) {
      validateFields(['date', 'courier_keyword'], (err, values) => {
        dispatch({
          type: 'cost/getCostList',
          payload: {
            page,
            start_time: moment(values.date[0]).format(dataFormat),
            end_time: moment(values.date[1]).format(dataFormat),
            courier_keyword: values.courier_keyword,
            size,
          },
        });
      });
    } else {
      dispatch({
        type: 'cost/getCostList',
        payload: {
          page,
          start_time: s_time || time,
          end_time: s_time || time,
          courier_id: detailId || id,
          is_detail: 1,
          size,
        },
      });
    }
  };

  selectedRowKeysHandle = (data, cb, type) => {
    const { dispatch } = this.props;
    const params = {
      collect_courier_id: [],
      date: [],
    };
    if (Array.isArray(data)) {
      data.length > 0 &&
        data.map(item => {
          params.collect_courier_id.push(item.collect_courier_id);
          params.date.push(item.arrived_ymd);
        });
    } else {
      this.setState({
        currentId: data.id,
      });
      params.collect_courier_id = data.collect_courier_id;
      params.date = data.arrived_ymd;
      if (type == 1) {
        params.order_id = data.id;
      }
    }
    dispatch({
      type: 'cost/giveCostOut',
      payload: params,
      callback: () => {
        this.getCostList();
        cb && cb();
      },
    });
  };

  handleSearch = debounce(
    e => {
      e.preventDefault();
      this.getCostList();
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  handleOk = () => {
    const {
      dispatch,
      cost: { singleCost },
      form: { validateFields },
    } = this.props;
    validateFields(['shipping_rule', 'fee', 'send'], (err, values) => {
      if (err) {
        return;
      }
      let params = {};
      if (values.shipping_rule == '1') {
        params = {
          ...values,
          money: values.fee,
        };
      } else {
        params = {
          ...values,
          rate: values.fee,
        };
      }
      if (singleCost) {
        params.id = singleCost.id;
      }
      dispatch({
        type: 'cost/costSetting',
        payload: params,
        callback: () => {
          this.handleCancel();
        },
      });
    });
  };

  openModal = () => {
    this.setState({ visible: true });
    const { dispatch } = this.props;
    dispatch({
      type: 'cost/getSingleCost',
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };

  getCostDetail = (id, time) => {
    this.setState({
      detailId: id,
      s_time: time,
    });
    this.cleanCosetList();
    this.getCostList(1, id, time);
  };

  closeDetail = () => {
    this.setState({
      detailId: '',
      s_time: '',
    });
    this.cleanCosetList();
    this.getCostList(1, '', '', true);
  };

  cleanCosetList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'cost/save',
      payload: {
        costList: {},
      },
    });
  };

  downloadData = () => {
    const {
      form: { getFieldValue },
    } = this.props;
    const { detailId, s_time } = this.state;
    const date = getFieldValue('date');
    const courier_keyword = getFieldValue('courier_keyword');
    let query = {
      run: '/Order/feeSettlementList',
      time: new Date().getTime(),
    };
    if (!detailId) {
      query = {
        data: JSON.stringify({
          data: {
            start_time: moment(date[0]).format(dataFormat),
            end_time: moment(date[1]).format(dataFormat),
            courier_keyword,
            is_excel: 1,
          },
          ...query,
        }),
      };
    } else {
      query = {
        data: JSON.stringify({
          data: {
            start_time: s_time,
            end_time: s_time,
            courier_keyword,
            courier_id: detailId,
            is_excel: 1,
            is_detail: 1,
          },
          ...query,
        }),
      };
    }
    return {
      ...query,
    };
  };

  radioChange = () => {
    const {
      form: { setFieldsValue },
    } = this.props;
    setFieldsValue({ fee: '' });
  };

  formatter = (value, type) =>
    (type === 0
      ? value > 100
        ? 100
        : `${value}`.replace(/\./g, '')
      : `${value}`.replace(/^(-)*(\d+)\.(\d).*$/, '$1$2.$3'));

  render() {
    const {
      form: { getFieldDecorator, getFieldValue },
      cost: { costList, singleCost },
      submitLoading,
      outLoading,
    } = this.props;
    let singleTupe = '';
    if (singleCost) {
      if (singleCost.shipping_rule == 0) {
        singleTupe = singleCost.rate;
      } else {
        singleTupe = singleCost.money;
      }
    }
    const { visible, detailId, currentId } = this.state;
    const columns = [
      {
        title: '完成日期',
        dataIndex: 'arrived_ymd',
      },
      {
        title: '配送员',
        render: (text, record) => (
          <div>
            {`${record.collect_courier_name}`}
            {record.collect_courier_mobile ? `(${record.collect_courier_mobile})` : ''}
          </div>
        ),
      },
      {
        title: '完成量',
        dataIndex: 'count',
      },
      {
        title: '总配送费',
        dataIndex: 'receipts_muns',
      },
      {
        title: '公司配送费',
        dataIndex: 'company_fee',
        render: (text, record) => (
          <span>{Math.round((record.receipts_muns - record.earnings_muns) * 100) / 100}</span>
        ),
      },
      {
        title: '配送员配送费',
        dataIndex: 'earnings_muns',
      },
      {
        title: '是否发放',
        render: (text, record) => (
          <div>
            {record.count == record.is_receipted_muns ? (
              <span>已发放</span>
            ) : record.is_receipted_muns == 0 ? (
              <span>未发放</span>
            ) : (
              <span>部分发放</span>
            )}
          </div>
        ),
      },
      {
        title: '操作',
        render: (text, record) => (
          <div>
            {!detailId && (
              <a
                style={{ marginRight: '30px' }}
                onClick={() => {
                  this.getCostDetail(record.collect_courier_id, record.arrived_ymd);
                }}
              >
                查看明细
              </a>
            )}

            {currentId == record.id && outLoading ? (
              <Spin />
            ) : (
              <a
                style={{ marginRight: '30px' }}
                onClick={() => {
                  this.selectedRowKeysHandle(record);
                }}
              >
                发放
              </a>
            )}
          </div>
        ),
      },
    ];
    const columnsDetail = [
      {
        title: '完成日期',
        dataIndex: 'arrived_ymd',
      },
      {
        title: '配送员',
        render: (text, record) => (
          <div>
            {`${record.collect_courier_name}`}
            {record.collect_courier_mobile ? `(${record.collect_courier_mobile})` : ''}
          </div>
        ),
      },
      {
        title: '订单编号',
        dataIndex: 'id',
      },
      {
        title: '总配送费',
        dataIndex: 'receipts',
      },
      {
        title: '公司配送费',
        dataIndex: 'company_fee',
        render: (text, record) => (
          <span>{Math.round((record.receipts - record.earnings) * 100) / 100}</span>
        ),
      },
      {
        title: '配送员配送费',
        dataIndex: 'earnings',
      },
      {
        title: '是否发放',
        dataIndex: 'is_receipted',
        render: text => (
          <div style={{ display: 'inline-block' }}>
            {text == '0' ? <span>未发放</span> : <span>已发放</span>}
          </div>
        ),
      },
      {
        title: '操作',
        render: (text, record) => (
          <div>
            {record.is_receipted == '0' ? (
              currentId == record.id && outLoading ? (
                <Spin />
              ) : (
                <a
                  style={{ marginRight: '30px' }}
                  onClick={() => {
                    this.selectedRowKeysHandle(record, '', 1);
                  }}
                >
                  发放
                </a>
              )
            ) : (
              ''
            )}
          </div>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="配送费结算">
        <div className={styles.main}>
          <Card bordered={false} bodyStyle={{ padding: '0 0 24px' }}>
            <Form onSubmit={this.handleSearch} className={styles['search-form']} layout="inline">
              <Row>
                <Col md={19} sm={24}>
                  <FormItem label="订单完成日期">
                    {getFieldDecorator('date', {
                      initialValue: [
                        moment(new Date()).add(-1, 'month'),
                        moment(new Date()).add(0, 'day'),
                      ],
                    })(
                      <RangePicker style={{ width: 240 }} placeholder={['开始日期', '结束日期']} />,
                    )}
                  </FormItem>
                  <FormItem label="配送员">
                    {getFieldDecorator('courier_keyword')(
                      <Input style={{ width: 200 }} placeholder="请输入配送员姓名或手机号" />,
                    )}
                  </FormItem>
                  <FormItem>
                    <Button
                      type="primary"
                      icon="search"
                      htmlType="submit"
                      disabled={detailId}
                      key="search"
                      loading={submitLoading}
                    >
                      查询
                    </Button>
                  </FormItem>
                </Col>
                <Col md={5} sm={24} style={{ textAlign: 'right' }}>
                  <FormItem style={{ marginRight: 0 }}>
                    <Button
                      icon="setting"
                      type="primary"
                      onClick={() => {
                        this.openModal();
                      }}
                    >
                      配送费结算及发放设置
                    </Button>
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Card>
          <div style={{ paddingBottom: '24px' }} className="flex-row justify-between">
            <div>
              <DownloadBar className="mr-10" href="/Api/Handle/run" query={this.downloadData}>
                <Button type="primary" icon="download">
                  {detailId ? '导出明细' : '导出'}
                </Button>
              </DownloadBar>
            </div>
            {detailId ? (
              <div>
                <a onClick={this.closeDetail}>关闭明细</a>
              </div>
            ) : (
              ''
            )}
          </div>
          <StandardTable
            rowKey="id"
            loading={submitLoading}
            selectedRows={detailId ? null : 'id'}
            data={costList}
            columns={detailId ? columnsDetail : columns}
            onChange={this.handleStandardTableChange}
            onSelectRowHandle={this.selectedRowKeysHandle}
            footer={{ name: '批量发放', loading: outLoading }}
          />
          <Modal
            destroyOnClose
            title="配送费结算及发放设置"
            visible={visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            centered
          >
            <div className={styles.cost}>
              <FormItem
                labelCol={{ span: 6 }}
                colon={false}
                wrapperCol={{ span: 16 }}
                label="结算规则"
              >
                {getFieldDecorator('shipping_rule', {
                  initialValue: singleCost ? singleCost.shipping_rule : '0',
                  rules: [
                    {
                      required: true,
                      message: '结算规则必选',
                    },
                  ],
                })(
                  <RadioGroup onChange={this.radioChange}>
                    <Radio value="0">按比例</Radio>
                    <Radio value="1">按金额</Radio>
                  </RadioGroup>,
                )}
              </FormItem>
              <Form layout="inline">
                <FormItem
                  colon={false}
                  label={`配送员每配送一单，${
                    getFieldValue('shipping_rule') == 0 ? '公司抽取实际配送费的' : '公司抽取配送费'
                  }`}
                >
                  {getFieldDecorator('fee', {
                    initialValue: singleTupe,
                    rules: [
                      {
                        required: true,
                        message: '公司抽取配送费不能为空',
                      },
                    ],
                  })(
                    getFieldValue('shipping_rule') == 0 ? (
                      <InputNumber
                        max={100}
                        min={0}
                        formatter={value => this.formatter(value, 0)}
                      />
                    ) : (
                      <InputNumber
                        parser={value => this.formatter(value, 1)}
                        formatter={value => this.formatter(value, 1)}
                      />
                    ),
                  )}
                </FormItem>
                <FormItem>{getFieldValue('shipping_rule') == 0 ? '%' : '元'}</FormItem>
              </Form>
            </div>
            <div className={styles.cost}>
              <FormItem
                labelCol={{ span: 6 }}
                colon={false}
                wrapperCol={{ span: 16 }}
                label="发放设置"
              >
                {getFieldDecorator('send', {
                  initialValue: singleCost ? singleCost.send : '0',
                  rules: [
                    {
                      required: true,
                      message: '发放设置必选',
                    },
                  ],
                })(
                  <RadioGroup>
                    <Radio value="1">自动发放</Radio>
                    <Radio value="0">手动发放</Radio>
                  </RadioGroup>,
                )}
              </FormItem>
            </div>
            <p style={{ color: '#f00' }}>修改设置后，立即生效</p>
          </Modal>
        </div>
      </PageHeaderLayout>
    );
  }
}
